package com.spreedairy.recommendation;

import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portlet.shopping.model.ShoppingItem;
import com.spreedairy.common.CommonAction;
import com.spreedairy.portal.service.RecommendationLocalServiceUtil;
import com.spreedairy.portal.service.WishlistLocalServiceUtil;

import java.io.IOException;
import java.util.List;

import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

public class RecommendationPortlet extends CommonAction{

	@Override
	public void doView(RenderRequest renderRequest,
			RenderResponse renderResponse) throws IOException, PortletException {
		ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
		List<Long> itemIds = RecommendationLocalServiceUtil.getTopRecommendationIds(themeDisplay.getCompanyId(), themeDisplay.getScopeGroupId());
		List<ShoppingItem> itemList = getItemList(itemIds);
		String link = ParamUtil.getString(renderRequest, "linkType");
		int start = 0;
		int end = 6;
		int pageCount = 1;
		if(Validator.isNotNull(link)){
			pageCount = ParamUtil.getInteger(renderRequest, "RECOMMENDATION_PAGE_COUNT");
			if(link.equalsIgnoreCase("previous")){
				pageCount = pageCount - 1;
			} else {
				pageCount = pageCount + 1;
			}
			end = pageCount * 6;
			start = end - 6;
		}
		renderRequest.setAttribute("RECOMMENDATION_LAST_PAGE", Boolean.FALSE);
		if(end >= itemList.size()) {
			end = itemList.size();
			renderRequest.setAttribute("RECOMMENDATION_LAST_PAGE", Boolean.TRUE);
		}
		itemList = itemList.subList(start, end);
		renderRequest.setAttribute("TOP_RECOMMENDATION", itemList);
		renderRequest.setAttribute("RECOMMENDATION_PAGE_COUNT", String.valueOf(pageCount));
		super.doView(renderRequest, renderResponse);
	}

}
